#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
wsite 入口文件
script name: hello
Created on 2020/2/13 21:16 by PyCharm
@author: fujianjian
"""
import os
from datetime import datetime

from flask import render_template, request, jsonify
from flask_migrate import Migrate

from app import create_app, db
from app.crawler import launch_seed_crawler
from app.model.actress import Actress
from app.model.plan import Plan, PlanItem
from app.model.seed import Seed, Production

wsite = create_app(os.environ.get('FLASK_ENV') or 'default')
migrate = Migrate(app=wsite, db=db, compare_type=True)

# launch_seed_crawler(app=wsite)

@wsite.shell_context_processor
def make_shell_context():
    return dict(db=db, Actress=Actress, Seed=Seed, Production=Production,
                Plan=Plan, PlanItem=PlanItem)


@wsite.route('/')
def index():
    return render_template('index.html', curr_time=datetime.utcnow())


@wsite.errorhandler(404)
def page_not_found(e):
    """
    统一的页面找不到错误处理类
    :param e:
    :return:
    """
    if request.accept_mimetypes.accept_json \
            and not request.accept_mimetypes.accept_html:
        response = jsonify({'error': 'not found'})
        response.status_code = 404
        return response
    return render_template('error.html', err_model={'title': 'http 404'})


@wsite.errorhandler(500)
def internal_error():
    if request.accept_mimetypes.accept_json \
            and not request.accept_mimetypes.accept_html:
        response = jsonify({'error': 'internal_error'})
        response.status_code = 500
        return response
    return render_template('error.html', err_model={'title': 'http 500'})
